package com.example.demo01.Impl.webImpl;

import com.example.demo01.Dao.webDao.BookDao;
import com.example.demo01.Entity.webEntity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class BookDaoImpl implements BookDao {
    //属性自动装配
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public List<Book> findAllBooks() {
        String sqlQuery="SELECT * FROM `book`";
        return jdbcTemplate.query(sqlQuery, new RowMapper<Book>() {
            @Nullable
            @Override
            public Book mapRow(ResultSet resultSet, int i) throws SQLException {
                return new Book(
                        resultSet.getInt(1),
                        resultSet.getString(2),
                        resultSet.getString(3),
                        resultSet.getString(4)
                );
            }
        });
    }

    @Override
    public List<Book> findBookByName(String name) {
        String sqlQuery="SELECT * FROM `book` WHERE book.b_name=?";
        return jdbcTemplate.query(sqlQuery,new Object[]{ name}, new RowMapper<Book>() {
            @Nullable
            @Override
            public Book mapRow(ResultSet resultSet, int i) throws SQLException {
                return new Book(
                        resultSet.getInt(1),
                        resultSet.getString(2),
                        resultSet.getString(3),
                        resultSet.getString(4)
                );
            }
        });
    }
}
